package com.wushe.thirdexample;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.internal.ChannelUtils;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @description:
 * @author: WuShe
 * @date: 2019/11/29 14:04
 * @version: 1.0.0
 * @modified By:
 */
public class MyChatServerHandle extends SimpleChannelInboundHandler<String> {
    private static  ChannelGroup group;
    static {
        group = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
        Channel channel = ctx.channel();
        group.forEach(ch->{
            if (channel!=ch){
                ch.writeAndFlush(channel.remoteAddress()+" 发送消息:"+s+"\n");
            }else {
                ch.writeAndFlush("【自己】"+s+"\n");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        group.writeAndFlush("[服务器]"+ctx.channel().remoteAddress()+",加入\n");
        group.add(ctx.channel());
    }
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        group.remove(ctx.channel());
        group.writeAndFlush("[服务器]"+ctx.channel().remoteAddress()+",下线\n");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("dfs");
        System.out.println(ctx.channel().remoteAddress()+"上线了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress()+"下线了");
    }
}
